package com.dao;

import com.domain.User;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UserUtils {
    private static File file = new File("/Users/edy/Desktop/user.txt");
    // 查找所有的User对象
    public static List<User> findAllUser() throws IOException {
        List<User> userList = new ArrayList<>();
        List<String> stringList = FileUtils.readLines(file, "UTF-8");
        for (String s : stringList) {
            User user = strToUser(s);
            userList.add(user);
        }
        return userList;
    }


    //增加User对象
    public static void addUser(User user) throws IOException {
        FileUtils.writeStringToFile(file,userToString(user),"UTF-8",true);
    }


    //删除User对象
    public static void deleteUser(String name) throws IOException {
        List<String> strlist = FileUtils.readLines(file, "UTF-8");
        FileUtils.writeStringToFile(file,"","UTF-8");
        for (String s : strlist) {
            User user = strToUser(s);
            if (!(user.getName().equals(name))) {
                addUser(user);
            }
        }
    }
    public static void updateUser(User newUser) throws IOException {
        List<String> strlist = FileUtils.readLines(file, "UTF-8");
        FileUtils.writeStringToFile(file,"","UTF-8");
        for (String s : strlist) {
            User user = strToUser(s);
            if (user.getName().equals(newUser.getName())) {
                user.setAge(newUser.getAge());
                user.setSex(newUser.getSex());
                user.setAddress(newUser.getAddress());
                addUser(user);
            } else {
                addUser(user);
            }
        }
        }

    //User转换成String
    public static String userToString(User user) {
        String str = user.getName()+","+user.getAge()+","+user.getSex()+","+user.getAddress()+"\n";
        return str;
    }


    //String转换成User
    public static User strToUser(String str) {
        String[] split = str.split(",");
        User user = new User(split[0],split[1],split[2],split[3]);
        return user;
    }

    public static void main(String[] args) throws IOException {

    }
}
